//Use a pool of threads. The  maximum number of threads in the 
//pool at any time is in the variable: NUMTHREADS. 
//When run, the prime pool will create threads to
//check primality. Each thread will cover a range
//of numbers.

package nachos.threads;
import nachos.machine.*;

class PrimePool implements Runnable
{
	public PrimePool(int start, int finish, int number_of_threads)
	{
		max = finish;					//the highest number to check
		NUMTHREADS = number_of_threads;
		exit = false;
		count = new int[1];
		count[0] = 0;					//the count of all current threads, must be an array for pass by reference
		lower = start;					//the first number to check
		upper = start + NUMTHREADS;		//the last number to check in the range
	}

	public void run()
	{
		while(!exit)
		{
			if (count[0] < NUMTHREADS)  //if there is room...
			{
				(new KThread(new DeterPrime(lower, upper, count))).fork(); //starts a thread to check the range
				lower = lower + NUMTHREADS;  //increase lower and upper
				upper = upper + NUMTHREADS;  //to a different range
			}
			
			if(lower >= max)  //if we have reached the highest number to check, then exit
				exit = true;
		}
	}
	
	private int NUMTHREADS;
	private boolean exit;
	private int[] count;  //must be an array so that we can pass by reference
	private int lower;
	private int upper;
	private int max;
}
